package com.room.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.room.pojo.DormResult;
import com.room.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @创建人 lin
 * @创建时间 2019/10/16
 * @描述
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    private String defaultFilterProcessUrl = "/login";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest)request;
        HttpServletResponse response1 = (HttpServletResponse)response;
        if ("POST".equalsIgnoreCase(request1.getMethod()) && defaultFilterProcessUrl.equals(request1.getServletPath())) {
            // 驗證碼驗證
            String requestCaptcha = request.getParameter("checkcode");
            String genCaptcha = (String) request1.getSession().getAttribute("checkcode");
            if (StringUtils.isEmpty(requestCaptcha)){
//            {  throw new AuthenticationServiceException("驗證碼不能爲空!");
                response1.setContentType("application/json;charset=utf-8");
                response1.setStatus(401);
                DormResult respBean = DormResult.error("验证码不能为空");
                ObjectMapper om = new ObjectMapper();
                PrintWriter out = response1.getWriter();
                out.write(om.writeValueAsString(respBean));
                out.flush();
                out.close();
            }
           else if (!genCaptcha.equals(requestCaptcha)) {
//                throw new AuthenticationServiceException("驗證碼錯誤!");
                response1.setContentType("application/json;charset=utf-8");
                response1.setStatus(401);
                DormResult respBean = DormResult.error("验证码错误");
                ObjectMapper om = new ObjectMapper();
                PrintWriter out = response1.getWriter();
                out.write(om.writeValueAsString(respBean));
                out.flush();
                out.close();
            }
        }
        chain.doFilter(request, response);
    }

}
